export function randomColor(index) {
  const color = ['success', 'info', 'warning', 'danger', '']
  return color[index % color.length]
}

export function getRandomIndex(list) {
  if (!list || list.length < 1) {
    return 0
  }
  const index = Math.ceil(Math.random() * (list.length - 1))
  return list[index]
}

export function getLocalImgFile(localPath, dict) {
  localPath = localPath.replaceAll('\\', '/')
  return (this.dict ? this.dict : dict).label.server_url['file_path'] + localPath + 'index.jpg'
}

export function getLocalM3U8File(localPath, dict) {
  localPath = localPath.replaceAll('\\', '/')
  return (this.dict ? this.dict : dict).label.server_url['file_path'] + localPath + 'index.m3u8'
}

export function format(str, ...params) {
  for (let i = 0; i < params.length; i++) {
    str = str.replace('%s', params[i])
  }
  return str
}

export function getRandomVideoUrl(pageNum) {
  pageNum = (pageNum === 0 || pageNum === undefined) ? 1 : pageNum
  const size = 1000
  const index = Math.floor(Math.random() * size) + (pageNum - 1) * size
  return format(this.dict.label.server_url['random_play_url'], pageNum, index)
}

export function setComicReadHistory(key, detailAlt) {
  window.localStorage.setItem(comicDetail + key, detailAlt)
}

export function getComicReadHistory(key) {
  return window.localStorage.getItem(comicDetail + key)
}

export function setLocalStorageArray(key, array) {
  window.localStorage.removeItem(arrayPre + key)
  window.localStorage.setItem(arrayPre + key, JSON.stringify(array))
}

export function getLocalStorageArray(key) {
  const localStorageArray = window.localStorage.getItem(arrayPre + key)
  return (localStorageArray !== 'undefined' && localStorageArray !== null && localStorageArray !== 'null') ? JSON.parse(localStorageArray) : null
}

export function removeLocalStorageItemForArrayByUrl(key, data) {
  let newArray = []
  const localStorageArray = getLocalStorageArray(key)
  if (localStorageArray !== null && localStorageArray !== 'null' && localStorageArray.length > 0) {
    localStorageArray.forEach((item) => {
      if (item.url !== data.url) {
        newArray = [...newArray, item]
      }
    })
    window.localStorage.setItem(arrayPre + key, JSON.stringify(newArray))
  }
}

export function setDownloadManageArray(array) {
  setLocalStorageArray(spiderConst.DOWNLOAD_QUEUE, JSON.stringify(array))
}

export function getDownloadManageItem() {
  return getLocalStorageArray(spiderConst.DOWNLOAD_QUEUE)
}

export function removeDownloadManageItem(data) {
  removeLocalStorageItemForArrayByUrl(spiderConst.DOWNLOAD_QUEUE, data)
}

// key值
export const spiderConst = {
  DOWNLOAD_QUEUE: 'download_queue'
}
// 类型前缀
const arrayPre = 'array_'
const comicDetail = 'comicDetail_'

